import http from "http";
import methods from "methods";
import Router from "./router/index.js";
import path from "path";
import init from "./middleware/init.js";
function Application() {
  this.settings = {}; // 调用set方法时存放的内容
  this.engines = {};
}

Application.prototype.lazy_route = function () {
  if (!this.router) {
    this.router = new Router(); // 将路由系统进行了懒加载处理（一般都是要加载的）
    this.router.use(init); // 内置的初始化
  }
};
//  存放模板配置

Application.prototype.render = function (filepath, data, callback) {
  const ext = "." + this.get("view engine");
  const dir = this.get("views");
  let render = this.engines[ext];
  // console.log(render);

  render(path.resolve(dir, filepath + ext), data, (err, template) => {
    callback(template);
  });
};

// 就是用于做应用的配置的
Application.prototype.set = function (key, value) {
  if (arguments.length == 1) {
    return this.settings[key];
  }
  this.settings[key] = value;
};
Application.prototype.use = function () {
  this.lazy_route();
  this.router.use(...arguments); //  交给路由系统来处理
};
Application.prototype.listen = function (...args) {
  const server = http.createServer((req, res) => {
    function done() {
      // 如果路由系统中的层不存在则调用此方法来结束响应
      res.end(`Cannot ${req.method} ${req.url}`);
    }
    // 交给路由系统来做匹配，如果匹配不到就调用done
    res.app = this; // 将应用对象放到res上
    this.router.handle(req, res, done);
  });
  server.listen(...args);
};
methods.forEach((method) => {
  // app.get() / app.post
  Application.prototype[method] = function (path, ...handlers) {
    if (method === "get") {
      if (arguments.length == 1) {
        // 获取配置
        return this.set(path); // 重载
      }
    }

    // 让路由系统处理逻辑
    this.lazy_route();
    this.router[method](path, handlers);
  };
});

Application.prototype.engine = function (ext, renderFn) {
  this.engines[ext] = renderFn;
};
export default Application;
